import {createStore} from 'vuex'

export const store = createStore({
  state() {
    return {
      hour: 0, //小时
      minute: 0, //分钟
      week: 1, //周
      day: 1, //天
      money: 500, //拥有的金钱
      employ: false, //是否显示雇佣窗口
      canEmploy: true, //是否可以雇佣
      fire: false, //是否显示解雇窗口
      fireId: '', //当前要解雇的厨师的id
      canFire: false, //是否可以解雇
      menuing: false, //是否正在点菜
      showPrompt: false, //是否显示提示窗口
      prompt: {
        content: '解约厨师成功,解约支出￥140',
        type: 'positive'
      }, //提示窗口内容
      cookerCnt: 1, //当前拥有厨师数量
      maxCookerCnt: 3, //当前可拥有最大厨师数量
      allCusList:[
        {
          id:1,
          name:'CUS1',
          avatar: require('../assets/images/379339-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:2,
          name:'CUS2',
          avatar: require('../assets/images/379444-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:3,
          name:'CUS3',
          avatar: require('../assets/images/379446-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:4,
          name:'CUS4',
          avatar: require('../assets/images/379448-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:5,
          name:'CUS5',
          avatar: require('../assets/images/iconfinder_Boss-3_379348.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:6,
          name:'CUS6',
          avatar: require('../assets/images/iconfinder_Man-16_379485.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:7,
          name:'CUS7',
          avatar: require('../assets/images/iconfinder_Rasta_379441.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:8,
          name:'CUS8',
          avatar: require('../assets/images/379339-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:9,
          name:'CUS9',
          avatar: require('../assets/images/379444-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:10,
          name:'CUS10',
          avatar: require('../assets/images/379446-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:11,
          name:'CUS11',
          avatar: require('../assets/images/379448-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:12,
          name:'CUS12',
          avatar: require('../assets/images/iconfinder_Boss-3_379348.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:13,
          name:'CUS13',
          avatar: require('../assets/images/iconfinder_Man-16_379485.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:14,
          name:'CUS14',
          avatar: require('../assets/images/iconfinder_Rasta_379441.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:15,
          name:'CUS15',
          avatar: require('../assets/images/iconfinder_Rasta_379441.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:16,
          name:'CUS16',
          avatar: require('../assets/images/iconfinder_Man-16_379485.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:17,
          name:'CUS17',
          avatar: require('../assets/images/iconfinder_Boss-3_379348.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
        {
          id:18,
          name:'CUS18',
          avatar: require('../assets/images/379448-512.png'),
          state: 'waiting',
          patience: 100,
          come:false,
          timer: null
        },
      ], //可能来的顾客列表
      cookList: [
        {
          id: '1',
          state: 'free',
          workday:[false, false,false,false,false,false,false], //本周工作记录,初始化为7天都未工作
          clickCnt:0 //点击次数，用来加速做菜
          // food: '炸酥Echarts'
        },
      ], //厨师列表
      waitingList: [], //等待队列
      customerList: [
        {
          id: 1,
          state: 'free',
        },
        {
          id: 2,
          state: 'free',
        },
        {
          id: 3,
          state: 'free',
        },
        {
          id: 4,
          state: 'free',
        },
      ], //就餐列表
      cusCnt: 0, //被占的座位数
      orderingCus: null, //正在点餐的顾客
      timer: null, //时间日期计时器
      waitAddTimer: null //等待队列计时器
    }
  },
  mutations: {
    initState() {
      this.commit('initCookerList')
      this.commit('startDataUpdating')
      this.commit('resumeAddWaiting')
      setTimeout(() => {
        this.commit('prompting', ['餐厅目前有空位，赶紧点击等位客人头像让客人入座点餐吧', 'negative'])
      },2000)
    },
    // 开启日期时间变换
    startDataUpdating(state) {
      // 每天240秒
      state.timer = setInterval(() => {
        if (state.minute < 60) {
          state.minute++
        } else if (state.hour < 3) {
          state.minute = 0
          state.hour++
          if (state.hour===1){
            this.commit('collectPayments') //每隔一个小时自动结账准备付款的订单
            state.maxCookerCnt = 6
            state.canEmploy = true
          }
        } else if (state.day < 7) {
          this.commit('resetAllCus') //一天结束，重置顾客状态
          this.commit('appeaseCusAutoLeave') //没有被安抚的顾客全部离开
          state.hour = 0
          state.day += 1
        } else {
          this.commit('payCookersSalary') //支付厨师一周工资
          state.day = 1
          state.week += 1
        }
      }, 500)
    },
    // 初始化厨师状态
    initCookerList(state) {
      state.cookList.forEach((ck) => {
        ck.state = 'free'
        this.commit('cookerWaiting', ck)
      })
    },
    // 重置所有顾客的状态
    resetAllCus(state){
      state.allCusList.forEach((cus) => {
        cus.come = false
        cus.patience = 100
        cus.state = 'waiting'
        cus.timer = null
      })
    },
    // 时间暂停
    pause(state) {
      // 暂停日期时间变化
      clearInterval(state.timer)
      // 暂停等待队列时间变化
      this.commit('pauseWaitingList')
      // 暂停新顾客到来
      this.commit('pauseAddWaitList')
      // 暂停厨师做餐时间变化
      this.commit('pauseCookList')
      // 暂停顾客等待用餐时间变化
      this.commit('pauseFoodList')
    },
    // 暂停等待队列时间变化
    pauseWaitingList(state) {
      state.waitingList.forEach((wt) => {
        clearTimeout(wt.timer)
      })
    },
    // 等待队列暂停添加人物
    pauseAddWaitList(state) {
      clearTimeout(state.waitAddTimer)
    },
    // 暂停厨师做菜
    pauseCookList(state) {
      state.cookList.forEach((ck) => {
        clearTimeout(ck.timer)
      })
    },
    // 暂停食物进度变化
    pauseFoodList(state) {
      state.customerList.forEach((cus) => {
        if (cus.state === 'waiting') {
          cus.foodList.forEach((fd) => {
            clearTimeout(fd.timer)
          })
        }
      })
    },
    // 时间继续
    resume() {
      // 开启日期时间变换
      this.commit('startDataUpdating')
      // 开启等待队列时间变换
      this.commit('resumeWaiting')
      // 开启新顾客到来
      this.commit('resumeAddWaiting')
      // 开启厨师做餐时间变化
      this.commit('resumeCooking')
      // 开启顾客等待用餐时间变化
      this.commit('resumeFoodWaiting')
    },
    // 重新开启等待队列
    resumeWaiting(state) {
      // 顾客耐心值随时间的减少而减少，减到0时从等待列表中删除
      for (let i = 0; i < state.waitingList.length; i++) {
        let wt = state.waitingList[i]
        wt.timer = setTimeout(function timer() {
          wt.patience -= 1
          if (wt.patience > 0) {
            wt.timer = setTimeout(timer, 100)
          } else {
            let idx = state.waitingList.findIndex((item) => {
              return item.id === wt.id
            })
            state.waitingList.splice(idx, 1)
          }
        }, 100)
      }
    },
    // 等待队列随机时间添加人物
    resumeAddWaiting(state) {
      let len = state.allCusList.length
      state.waitAddTimer = setTimeout(function addWait() {
        let cus = state.allCusList[Math.floor(Math.random() * len)]
        if (state.waitingList.length < 5) {
          if (cus.come === false){
            let wt = JSON.parse(JSON.stringify(cus))
            state.waitingList.push(wt)
            wt.timer = setTimeout(function time() {
              wt.patience--
              if (wt.patience > 0) {
                wt.timer = setTimeout(time, 100)
              } else {
                let idx = state.waitingList.findIndex((item) => {
                  return item.id === wt.id
                })
                state.waitingList.splice(idx, 1)
              }
            }, 100)
          }
        }
        cus.come = true
        state.waitAddTimer = setTimeout(addWait, 4000)
      }, 3000)
    },
    // 厨师做菜继续
    resumeCooking(state) {
      state.cookList.forEach((ck) => {
        this.commit('cookerWaiting', ck)
      })
    },
    // 开启顾客等待用餐时间变化
    resumeFoodWaiting(state) {
      state.customerList.forEach((cus) => {
        if (cus.state === 'waiting') {
          cus.foodList.forEach((item) => {
            if (item.state === 'waiting') {
              item.timer = setTimeout(function time() {
                item.patience--
                if (item.patience > 0) {
                  item.timer = setTimeout(time, item.doingTime)
                }
              }, item.doingTime)
            }
          })
        }
      })
    },
    // 顾客点餐
    ordering(state) {
      if (state.cusCnt >= 4) {
        this.commit('prompting', ['餐厅位置已满', 'negative'])
        return
      }
      this.commit('pause')
      state.orderingCus = state.waitingList[0]
      // 从等待队列中删除第一个顾客
      state.waitingList.splice(0, 1)
      state.menuing = true
    },
    // 顾客点完餐找座位坐下
    sitDown(state, [list, pay]) {
      // 重新开始计时
      this.commit('resume')
      // 找空坐
      let idx = state.customerList.findIndex((item) => {
        return item.state === 'free'
      })
      if (idx !== -1) {
        state.cusCnt++;
        state.orderingCus.state = 'siting'
        state.orderingCus.foodList = JSON.parse(JSON.stringify(list))
        state.orderingCus.foodCnt = list.length //有效订单数量，用于计算顾客是否需要安抚或结账
        state.orderingCus.foodList.forEach((fd) => {
          fd.cus = state.orderingCus
          this.commit('patienceTimer', fd)
        })
        state.orderingCus.pay = pay
        state.customerList[idx] = state.orderingCus
        state.menuing = false
      }
      this.commit('prompting', [state.orderingCus.name+'点餐完成，等候用餐，疯狂点击厨师头像可以加速做菜', 'positive'])
    },
    // 顾客离开
    leave(state) {
      // 菜单隐藏
      state.menuing = false
      // 正在点餐人设为null
      state.orderingCus = null
      // 重新启动
      this.commit('resume')
    },
    // 设置顾客等菜和吃菜的时钟
    patienceTimer(state, fd) {
      fd.patienceTmr = function time() {
        // 顾客进食时间比等待时间短
        if (fd.state==='eating'){
          fd.patience--
        }
        fd.patience--
        if (fd.patience > 0) {
          fd.timer = setTimeout(time, fd.doingTime)
        } else {
          if (fd.state === 'eating') {
            fd.state = 'eatup'
          } else if (fd.state === 'doing' || fd.state === 'waiting') {
            fd.state = 'destroy'
          }
          let idx = fd.cus.foodList.findIndex((item) => {
            return item.state !== 'eatup' && item.state !== 'destroy'
          })
          if (idx === -1) {
            let idx2 = fd.cus.foodList.findIndex((item) => {
              return item.state === 'eatup'
            })
            if (idx2 === -1) {
              fd.cus.state = 'appease'
            } else {
              fd.cus.state = 'pay'
            }
          }
        }
      }
      fd.timer = setTimeout(fd.patienceTmr, fd.doingTime)
    },
    // 安抚顾客并让其离开
    appeaseCus(state, id) {
      let idx = state.customerList.findIndex((cus) => {
        return cus.id === id
      })
      this.commit('prompting', [state.customerList[idx].name + '失望而归，别再让客人挨饿了', 'negative'])
      state.customerList[idx].name = ''
      state.customerList[idx].avatar = ''
      state.customerList[idx].foodList = []
      state.customerList[idx].state = 'free'
      state.cusCnt--
      if (state.cusCnt === 0 && state.waitingList.length > 0) {
        let timer = setTimeout(() => {
          if (state.cusCnt!==0){
            clearTimeout(timer)
          }
          this.commit('prompting', ['餐厅目前有空位，赶紧点击等位客人头像让客人入座点餐吧', 'negative'])
        },1000)
      }
    },
    // 一天过后没有被安抚的顾客自动离开
    appeaseCusAutoLeave(state){
      state.customerList.forEach( (cus) => {
        if (cus.state === 'appease'){
          this.commit('prompting', [cus.name + '失望而归，别再让客人挨饿了', 'negative'])
          cus.name = ''
          cus.avatar = ''
          cus.foodList = ''
          cus.state = 'free'
          state.cusCnt--
        }
      })
      if (state.cusCnt === 0 && state.waitingList.length > 0) {
        let timer = setTimeout(() => {
          if (state.cusCnt!==0){
            clearTimeout(timer)
          }
          this.commit('prompting', ['餐厅目前有空位，赶紧点击等位客人头像让客人入座点餐吧', 'negative'])
        },1000)
      }
    },
    // 顾客支付
    payCus(state, id) {
      let idx = state.customerList.findIndex((cus) => {
        return cus.id === id
      })
      let pay = 0
      state.customerList[idx].foodList.forEach((fd) => {
        if (fd.state === 'eatup') {
          pay += fd.price
        }
      })
      state.money += pay
      this.commit('prompting', ['结账成功，成功收入￥' + pay + '', 'positive'])
      state.customerList[idx].name = ''
      state.customerList[idx].avatar = ''
      state.customerList[idx].foodList = []
      state.customerList[idx].state = 'free'
      state.cusCnt--
      if (state.cusCnt === 0 && state.waitingList.length > 0) {
        setTimeout(() => {
          this.commit('prompting', ['餐厅目前有空位，赶紧点击等位客人头像让客人入座点餐吧', 'negative'])
        },1000)
      }
    },
    //每隔一个小时自动结账准备付款的订单
    collectPayments(state){
      let pay = 0
      state.customerList.forEach( (cus) => {
        if (cus.state==='pay'){
        cus.foodList.forEach((fd) => {
            if (fd.state === 'eatup') {
              pay += fd.price
            }
          })
          cus.name = ''
          cus.avatar = ''
          cus.foodList = ''
          cus.state = 'free'
          state.cusCnt--
        }
      })
      state.money += pay
      if (pay>0)
      this.commit('prompting', ['结账成功，成功收入￥' + pay , 'positive'])
    },
    // 厨师时钟变化
    cookerWaiting(state, ck) {
      ck.waiting = function waiting() {
        let fd = null
        let cs = null
        // 寻找耐心值等待时间最短的食物
        let minPat = 101
        state.customerList.forEach((cus) => {
          // 如果是坐下或吃的状态，有可能还有菜需要做
          if (cus.state === 'siting' || cus.state === 'eating') {
            cus.foodList.forEach((food) => {
              if (food.state === 'waiting' && food.patience < minPat) {
                fd = food
                cs = cus
              }
            })
          }
        })
        if (fd === null) {
          ck.timer = setTimeout(waiting, 100)
        } else { // 如果找到了要做的食物，清空等待计时器，开启工作计时器
          ck.state = 'working'
          ck.workday[state.day-1] = true //当天工作记录为true
          ck.food = fd.name
          fd.state = 'doing'
          state.money -= Math.floor(fd.price/2) //假设做菜成本为价格的一半
          ck.fd = fd
          ck.cs = cs
          ck.progress = 0
          ck.timer = setTimeout(ck.working, 100)
        }
      }
      ck.working = function working() {
        ck.progress++
        if (ck.progress < 100) {
          ck.timer = setTimeout(working, 50)
        } else {
          ck.state = 'complete'
          if (ck.fd.state === 'doing') {
            ck.fd.state = 'completed'
            ck.fd.cooker = ck
            clearTimeout(ck.fd.timer)
          } else {
            ck.cwt = 50
            ck.timer = setTimeout(ck.completeWaiting, 100)
          }
        }
      }
      ck.completeWaiting = function completeWaiting() {
        ck.cwt--
        let nfd = null
        let ncs = null
        state.customerList.forEach((cus) => {
          if (cus.state !== 'free') {
            cus.foodList.forEach((food) => {
              if (food.name === ck.food && food.state === 'waiting') {
                nfd = food
                ncs = cus
              }
            })
          }
        })
        if (nfd !== null) {
          ck.state = 'complete'
          ck.cs = ncs
          nfd.state = 'completed'
          nfd.cooker = ck
          clearTimeout(nfd.timer)
        } else if (ck.cwt > 0) {
          ck.timer = setTimeout(completeWaiting, 100)
        } else {
          ck.state = 'free'
          ck.timer = setTimeout(ck.waiting, 100)
        }
      }
      if (ck.state === 'free') {
        ck.timer = setTimeout(ck.waiting, 100)
      } else if (ck.state === 'working') {
        ck.timer = setTimeout(ck.working, 100)
      } else if (ck.state === 'complete') {
        if (ck.fd.state !== 'completed') {
          ck.timer = setTimeout(ck.completeWaiting, 100)
        }
      }
    },
    // 支付厨师一周工资
    payCookersSalary(state){
      let pay = 0
      state.cookList.forEach( (cooker) => {
        for (let i = 0;i<cooker.workday.length;i++){
          if (cooker.workday[i] === true){
            pay+=20
          }
          cooker.workday[i] = false
        }
      })
      state.money-=pay
      this.commit('prompting',['第'+state.week+'周接结束，共支付厨师工资￥'+pay,'positive'])
    },
    // 雇佣厨师
    employed(state) {
      if (state.money < 100) {
        this.commit('prompting', ['您当前余额不足以雇佣新厨师！', 'negative'])
        return
      }
      state.money -= 100
      state.employ = false
      let ck = {
        id: Number(Math.random().toString().substr(3, 9) + Date.now()).toString(36),
        state: 'free',
        clickCnt:0,
        workday:[false, false,false,false,false,false,false], //本周工作记录,初始化为7天都未工作
      }
      this.commit('cookerWaiting', ck)
      state.cookList.push(ck)
      state.cookerCnt += 1
      if (state.cookerCnt > 1) {
        state.canFire = true
      }
      if (state.cookerCnt >= state.maxCookerCnt) {
        state.canEmploy = false
      }
      this.commit('prompting', ['招聘成功,您已经有' + state.cookerCnt + '名厨师', 'positive'])
    },
    // 显示雇佣厨师提示框
    employing(state) {
      state.employ = true
    },
    // 取消雇佣
    employCancel(state) {
      state.employ = false
    },
    // 显示解雇厨师提示框
    fireing(state, id) {
      state.fireId = id
      state.fire = true
    },
    // 解雇厨师
    fired(state) {
      if (state.money < 140) {
        this.commit('prompting', ['您的金额已经不足支付解约金', 'negative'])
        return
      }
      state.money -= 140
      state.cookerCnt -= 1
      state.canEmploy = true
      if (state.cookerCnt <= 1) {
        state.canFire = false
      }
      let idx = state.cookList.findIndex((item) => {
        return item.id === state.fireId
      })
      state.cookList.splice(idx, 1)
      state.fire = false
      this.commit('prompting', ['解约厨师成功，解约支出￥140', 'positive'])
    },
    // 取消解雇
    fireCancel(state) {
      state.fireId = ''
      state.fire = false
    },
    // 显示提示框
    prompting(state, [str, type]) {
      state.prompt.content = str
      state.prompt.type = type
      state.showPrompt = true
      setTimeout(() => {
        state.showPrompt = false
      }, 2000)
    },
    // 隐藏提示框
    cancelShowPrompt(state){
      state.showPrompt = false
    }
  }
})
